package logic

import (
	"context"

	"database/sql"
	"demo/internal/errorx"
	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"

	"strconv"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)




type ServeyClasifyCreateLogic struct{
	logx.Logger
	ctx context.Context
	svcCtx *svc.ServiceContext
	model model.ServeyClassifyModel
}

func NewServeyClassifyCreateLogic(ctx context.Context,svcCtx *svc.ServiceContext)*ServeyClasifyCreateLogic{
	return &ServeyClasifyCreateLogic{
		Logger: logx.WithContext(ctx),
		ctx: ctx,
		svcCtx: svcCtx,
		model: model.NewServeyClassifyModel(svcCtx.Orm,svcCtx.GormDB),
	}
}

func (l *ServeyClasifyCreateLogic)Create(req *types.ServeyClassifyCreateRequest)(resp *types.ServeyClassifyCreateResponse,err error){
	
	payload,ok := l.ctx.Value("payload").(string)
	if !ok{
		return nil,errorx.NewBizError(500,"用户ID获取失败")
	}
	userId,err := strconv.ParseInt(payload,10,64)
	if err != nil{
		return nil,errorx.NewBizError(500,"字符串格式转换错误")
	}

	// step1 judge data valid such as not empty 、valid
	namelen := len(strings.TrimSpace(req.ClfName))
	if namelen == 0 || namelen > 50 {
		return nil,errorx.NewBizError(500,"分类名长度不合规")
	}
	// step2 judge data isn't same database data
	sc1,err := l.model.FindOneByNameAndCreatorID(l.ctx,req.ClfName,userId)
	if sc1 != nil || (err != nil && err != model.ErrNotFound) {
		return nil,errorx.NewBizError(500,"分类名已存在，请重新取名")
	}
	// step3 insert it
	sc := &model.ServeyClassify{
		ClfName: req.ClfName,
		ClfDesc: sql.NullString{String: req.ClfDesc,Valid: true,},
		CreatorId: int64(userId),
	}
	scId,err := l.model.InsertGetId(l.ctx,nil,sc)
	if err != nil{
		return nil,errorx.NewBizError(500,"插入失败，请重试")
	}
	return &types.ServeyClassifyCreateResponse{
		Data: &types.IdResponse{
			Id: scId,
		},
		CommonResponse: types.CommonResponse{
			Code: 200,
			Msg: "insert success",
		},
	},nil
}

